/**
 *   类说明
 * 
 *   @creator         xldc	497937995@qq.com  
 *   @create-time     2014年1月11日   下午4:19:16   
 */
package com.huacheng.cms.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.huacheng.cms.constant.AdminConstant;
import com.huacheng.cms.dao.AdminMapper;
import com.huacheng.cms.exception.BaseException;
import com.huacheng.cms.model.Admin;
import com.huacheng.cms.model.vo.PageVo;
import com.huacheng.cms.util.AuthUtils;

@Service
public class AdminService {

	@Autowired
	private AdminMapper adminM;

	public boolean addOne(Admin admin) throws BaseException {
		int selects = -1;
		Admin a = new Admin();
		a.setName(admin.getName());
		a.setEmail(admin.getEmail());
		selects = adminM.selectBySelectiveCount(a);
		if (selects == 0) {
			admin.setPassword(AuthUtils.getPassword(admin.getPassword(), admin.getEmail()));
			admin.setCreatetime(new Date());
			if (admin.getFolderid() == null)
				admin.setFolderid(Long.valueOf(0));
			if (admin.getStatus() == null) {
				admin.setStatus(AdminConstant.Status.init.toString());
			}
			adminM.insertSelective(admin);
		} else {
			return false;
		}
		return true;
	}

	public Admin getOneByKey(long adminid) {
		return adminM.selectByPrimaryKey(adminid);
	}

	public Admin getAdminByEmail(String email) {
		return adminM.getAdminByEmail(email);
	}

	public void hidenByKey(long adminid) {
		Admin a = new Admin();
		a.setAdminid(adminid);
		a.setStatus(AdminConstant.Status.freeze.toString());
		adminM.updateByPrimaryKeySelective(a);
	}

	public int deleteOneByKey(long adminid) {
		return adminM.deleteByPrimaryKey(adminid);
	}

	public int updateOneByObj(Admin admin) throws BaseException {
		if (!admin.getPassword().equals("")) {
			admin.setPassword(AuthUtils.getPassword(admin.getPassword(), admin.getEmail()));
		}
		admin.setLasttime(new Date());
		return adminM.updateByPrimaryKeySelective(admin);
	}

	public int getListCountByObj(Admin admin) {
		return adminM.selectBySelectiveCount(admin);
	}

	public List<Admin> getListByObj(Admin admin, long offset, long rows) {
		return adminM.selectBySelective(admin, offset, rows);
	}

	public PageVo<Admin> getAllListPage(int pageNum) {
		PageVo<Admin> pageVo = new PageVo<Admin>(pageNum);
		pageVo.setRows(5);
		List<Admin> list = this.getListByObj(new Admin(), pageVo.getOffset(), pageVo.getRows());
		pageVo.setList(list);
		pageVo.setCount(this.getListCountByObj(new Admin()));
		return pageVo;
	}
}
